﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ElingOA6_Admin_DSJCJ.Common;
using System.Data;
using DevExpress.Web.Mvc;
using ElingOA6_Admin_DSJCJ.Models;
using DevExpress.Web.ASPxUploadControl;
using System.IO;

namespace ElingOA6_Admin_DSJCJ.Areas.Admin.Controllers
{
    /// <summary>
    /// 一事一议项目申请
    /// </summary>
    [OutputCache(Duration = 0, VaryByParam = "none")]
    public class OnePrjOneDiscusController : AdminBaseController
    {
        //
        // GET: /Admin/OnePrjOneDiscus/
        /// <summary>
        /// 一事一议项目申请主页
        /// </summary>
        /// <returns>视图</returns>
        [AuthorityActionFilter("m_OnePrjOneDiscussq", Order = 1)]
        [LogPageActionFilter("一事一议项目申请 ", Order = 2)]
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 列表显示
        /// </summary>
        /// <returns>视图</returns>
        public ActionResult OnePrjOneDiscusList() {

            int pageIndex = 1;
            List<Model.OnePrjOneDiscus> onePrjOneDiscusList = GetOnePrjOneDiscusList(pageIndex);

            return View(onePrjOneDiscusList);
        }

        /// <summary>
        /// 用于刷新
        /// </summary>
        /// <returns>视图</returns>
        public ActionResult OnePrjOneDiscusListPartial() {
            int pageIndex = Request.Params["pageIndex"] == null ? 0 : int.Parse(Request.Params["pageIndex"].ToString());
            int pageCount = Request.Params["PageCount"] == null ? 0 : int.Parse(Request.Params["PageCount"].ToString());
            int pageRowSize = Request.Params["pageRowSize"] == null ? 0 : int.Parse(Request.Params["pageRowSize"].ToString());
            int pageRowCount = Request.Params["pageRowCount"] == null ? 0 : int.Parse(Request.Params["pageRowCount"].ToString());

            string id = Request.Params["id"];
            string callbackArg = DevExpressHelper.CallbackArgument;
            string command = Request.Params["command"] == null ? "" : Request.Params["command"].ToString();

            if (command == "PAGERONCLICK")
            {
                string[] args = callbackArg.Split(new char[1] { '|' });
                string arg = args[args.Count() - 1];

                switch (arg)
                {
                    case "PBN;":
                        {
                            //下一页
                            pageIndex = pageIndex + 2;
                            break;
                        }
                    case "PBP;":
                        {
                            //上一页
                            //pageIndex = pageIndex;
                            break;
                        }
                    case "PBL;":
                        {
                            //最后一页
                            pageIndex = pageCount;
                            break;
                        }
                    case "PBF;":
                        {
                            //第一页
                            pageIndex = 1;
                            break;
                        }
                    default:
                        {
                            //点击数字页码
                            string tempIndex = arg.Replace("PN", "");
                            tempIndex = tempIndex.Replace(";", "");
                            if (RegExp.IsNumeric(tempIndex))
                            {
                                pageIndex = int.Parse(tempIndex) + 1;
                            }
                            break;
                        }

                }
            }
            else
            {
                pageIndex = pageIndex + 1;
            }


            List<Model.OnePrjOneDiscus> OnePrjOneDiscusList = GetOnePrjOneDiscusList(pageIndex, pageCount, pageRowSize);


            return PartialView("OnePrjOneDiscusListPartial", OnePrjOneDiscusList);
        }


        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageCount">每页显示大小</param>
        /// <param name="pageRowSize">每页显示页数</param>
        /// <returns>一事一议列表</returns>
        private List<Model.OnePrjOneDiscus> GetOnePrjOneDiscusList(int pageIndex, int pageCount = 0, int pageRowSize = 0)
        {
            BLL.Common commonBll = new BLL.Common();
            BLL.OnePrjOneDiscus onePrjOneDiscusBll = new BLL.OnePrjOneDiscus();
            string fiedls = "*";
            int total;
            string where = "FInsEmpNo = '" + OperateSession.get("FEmplNo") + "'";

            DataSet ds = commonBll.GetListByPage("v_OnePrjOneDiscus", fiedls, Common.GlobalConstant.CONSTRING_PAGESIZE, pageIndex, where, "FOnePrjOneDiscusID", 1, out total);

            List<Model.OnePrjOneDiscus> onePrjOneDiscusAllList = new List<Model.OnePrjOneDiscus>();
            List<Model.OnePrjOneDiscus> onePrjOneDiscusList = onePrjOneDiscusBll.DataTableToListOnePrjOneDiscus(ds.Tables[0]);

            pageRowSize = Common.GlobalConstant.CONSTRING_PAGESIZE;
            for (int i = 0; i < total; i++)
            {
                onePrjOneDiscusAllList.Add(null);
            }
            for (int i = 0; i < pageRowSize; i++)
            {
                if (onePrjOneDiscusList.Count > i)
                {
                    onePrjOneDiscusAllList[((pageIndex - 1) * pageRowSize) + i] = onePrjOneDiscusList[i];
                }
            }

             return onePrjOneDiscusAllList;
        }

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="id">一事一议ID</param>
        /// <returns>视图</returns>
        public ActionResult OnePrjOneDiscusContent(string id) {
            Model.OnePrjOneDiscus onePrjOneDiscusModel = new Model.OnePrjOneDiscus();
            BLL.OnePrjOneDiscus onePrjOneDiscusBll = new BLL.OnePrjOneDiscus();
            BLL.HRDept deptBll = new BLL.HRDept();

            string deptNo = OperateSession.get(GlobalConstant.PARAM_DEPTNO);
            string entityNo = GlobalConstant.ENTITYNO;
            string isAgency = deptBll.IsAgency(deptNo, entityNo);


            if (string.IsNullOrEmpty(id))
            {
                if (isAgency == "Y")
                {
                    onePrjOneDiscusModel.FYear = DateTime.Now.Year;
                    onePrjOneDiscusModel.FisPoor = "N";
                    onePrjOneDiscusModel.FDeptNo = deptNo;
                }
                else
                {
                    onePrjOneDiscusModel.FYear = DateTime.Now.Year;
                    onePrjOneDiscusModel.FisPoor = "N";
                }
                ViewData["type"] = "ADD";
            }
            else
            {
                id = Fetch.estimateString(id, CheckGetEnum.Safety);
                onePrjOneDiscusModel = onePrjOneDiscusBll.GetModel(decimal.Parse(id));
                ViewData["id"] = id;
                ViewData["type"] = "Edit";
            }
            ///年度
            List<SelectListItem> itemList = new List<SelectListItem>();
            SelectListItem item;
            string year = string.Empty;
            for (int i = DateTime.Now.Year; i >= 2009; i-- )
            {
                item = new SelectListItem();
                year = i.ToString();
                item.Text = year;
                item.Value = year;
                itemList.Add(item);
            }

            ViewData["year"] = itemList;

            ///乡镇绑定登陆         

            List<SelectListItem> items = new List<SelectListItem>();
            if (isAgency == "N")
            {
                List<Model.HRDept> deptList = deptBll.GetListEntityNo(entityNo);
                foreach (Model.HRDept model in deptList)
                {
                    items.Add(new SelectListItem() { Text = model.FDeptName, Value = model.FDeptNo });
                }
            }
            else 
            {
                string deptName = deptBll.GetDeptName(entityNo, deptNo);
                items.Add(new SelectListItem() { Text = deptName, Value = deptNo });
            }
            ViewData["Dept"] = items;

            return View(onePrjOneDiscusModel);
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="onePrjOneDiscusModel">对象</param>
        /// <returns>视图</returns>
        public ActionResult Save(Model.OnePrjOneDiscus onePrjOneDiscusModel)
        {        
            if (Fetch.Post("hidid") == "" || Fetch.Post("hidid") == null)
            {
                onePrjOneDiscusModel.FOnePrjOneDiscusID = onePrjOneDiscusModel.FOnePrjOneDiscusID;
            }
            else {
                onePrjOneDiscusModel.FOnePrjOneDiscusID = decimal.Parse(Fetch.Post("hidid"));
            }

            onePrjOneDiscusModel.FTitle = Fetch.Post("tbFTitle");
            onePrjOneDiscusModel.FDeptNo = ComboBoxExtension.GetValue<string>("tbFDeptNo");
            onePrjOneDiscusModel.FEntityNo = GlobalConstant.ENTITYNO;
            onePrjOneDiscusModel.FYear = ComboBoxExtension.GetValue<decimal>("tbFYear");
            onePrjOneDiscusModel.FNote = Fetch.Post("tbFNote");
            onePrjOneDiscusModel.FisPoor = RadioButtonListExtension.GetValue<string>("tbFisPoor");

            ///附件上传
            UploadedFile[] uploadFiles = UploadControlExtension.GetUploadedFiles("uploaddoc");
            if (uploadFiles.Length > 0 && null != uploadFiles)
                {
                    for (int i = 0; i < uploadFiles.Length; i++)
                    {
                        UploadedFile upload = uploadFiles[i];
                        if (upload != null)
                        {                        
                            string backname = upload.FileName.Substring(upload.FileName.LastIndexOf('.') + 1);
                         
                            string entityNo = GlobalConstant.ENTITYNO;

                            string dest_dir = "Publish/ysyy/" + entityNo + "/upload/";
                        
                            string svrFileName = Path.GetFileNameWithoutExtension(upload.FileName);//上传的文件名
                         
                            string uploadoffiepath = Server.MapPath(Url.Content("~") + dest_dir);//上传文件的路径

                            if (!Directory.Exists(uploadoffiepath))//如果不存在就创建
                            {
                                Directory.CreateDirectory(uploadoffiepath);
                            }

                            upload.SaveAs(uploadoffiepath + svrFileName + "." + backname);

                            onePrjOneDiscusModel.FAttachOldFileName = Path.GetFileNameWithoutExtension(upload.FileName) + Path.GetExtension(upload.FileName).ToLower();
                            onePrjOneDiscusModel.FAttachSvrFileName = Url.Content("~") + dest_dir + Path.GetFileNameWithoutExtension(upload.FileName) + Path.GetExtension(upload.FileName).ToLower();
                            onePrjOneDiscusModel.FAttachFileExt = backname;
                        }
                    }
                }

            onePrjOneDiscusModel.FInsDate = DateTime.Now;
            onePrjOneDiscusModel.FInsEmpNo = OperateSession.get("FEmplNo");
            onePrjOneDiscusModel.FInsIP = Common.GenerateUtil.GetClientIPv4Address();

            onePrjOneDiscusModel.FUpdDate = null;
            onePrjOneDiscusModel.FUpdEmpNo = "";
            onePrjOneDiscusModel.FUpdIP = "";
            onePrjOneDiscusModel.FCheckEmpNo = "";
            onePrjOneDiscusModel.FCheckDate = null;
            onePrjOneDiscusModel.FCheckIP = "";
            onePrjOneDiscusModel.FStatus = "";

            BLL.OnePrjOneDiscus onePrjOneDiscusBll = new BLL.OnePrjOneDiscus();
            string type = Fetch.Post("hdtype");
            try
            {
                ///增加
                if (type == "ADD")
                {
                    onePrjOneDiscusBll.Add(onePrjOneDiscusModel);
                }
                 ///修改
                else if (type == "Edit")
                {
                    onePrjOneDiscusModel.FUpdDate = DateTime.Now;
                    onePrjOneDiscusModel.FUpdEmpNo = OperateSession.get("FEmplNo");
                    onePrjOneDiscusModel.FUpdIP = Common.GenerateUtil.GetClientIPv4Address();
                    onePrjOneDiscusBll.Update(onePrjOneDiscusModel);

                }
                ViewData["message"] = "操作成功";
                ViewData["IsClose"] = "Y";

            }
            catch (Exception) {

                ViewData["message"] = "操作失败";
                ViewData["IsClose"] = "N";
            }                    
        return View("OnePrjOneDiscusContent", onePrjOneDiscusModel);
      
    }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public string DeleteMany(string ids) {
            string str = "";
            string strEntityNo = GlobalConstant.ENTITYNO;
            string[] idArray = ids.Split(new string[] { "%!^" }, StringSplitOptions.RemoveEmptyEntries);
            BLL.OnePrjOneDiscus onePrjOneDiscusBll = new BLL.OnePrjOneDiscus();
            List<string> docPathList = GetManyPathList(idArray, strEntityNo);
            try
            {
                onePrjOneDiscusBll.DeleteMany(idArray);
                DeleteDoc(docPathList);//删除保存在硬盘的图片
                str = "ok";
            }
            catch (Exception)
            {
                str = "error";
            }

            return str;
        
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id">主键id</param>
        /// <returns></returns>
        public string Del(string id) {
            string str = "";
            string strEntityNo = GlobalConstant.ENTITYNO;
            BLL.OnePrjOneDiscus onePrjOneDiscusBll = new BLL.OnePrjOneDiscus();
            List<string> docPathList = GetPathList(id, strEntityNo);//获取保存在硬盘中的图片路径list
            try
            {
                onePrjOneDiscusBll.Delete(decimal.Parse(id));
                DeleteDoc(docPathList);//删除保存在硬盘的图片
                str = "ok";
            }
            catch (Exception)
            {
                str = "error";
            }

            return str;
        
        }
        /// <summary>
        /// 获取保存在硬盘中的图片路径
        /// </summary>
        /// <param name="strAdCds">广告编号</param>
        /// <param name="strEntityNo">公司编号</param>
        /// <returns>图片路径</returns>

        public List<string> GetPathList(string id, string strEntityNo)
        {
            BLL.OnePrjOneDiscus onePrjOneDiscusBll = new BLL.OnePrjOneDiscus();
            List<string> strList = onePrjOneDiscusBll.GetSrvName(id, strEntityNo);
            return strList;
        }
        /// <summary>
        /// 删除保存在硬盘的图片
        /// </summary>
        /// <param name="strList">图片路径list</param>
        public void DeleteDoc(List<string> strList)
        {
            foreach (string strPath in strList)
            {
                GenerateUtil.DeleteFile(Url.Content("~") + strPath);
            }
        }
        /// <summary>
        /// 获取保存在硬盘中的图片路径 批量删除
        /// </summary>
        /// <param name="strAdCds">广告编号</param>
        /// <param name="strEntityNo">公司编号</param>
        /// <returns>图片路径</returns>

        public List<string> GetManyPathList(string[] ids, string strEntityNo)
        {
            BLL.OnePrjOneDiscus onePrjOneDiscusBll = new BLL.OnePrjOneDiscus();
            List<string> strList = onePrjOneDiscusBll.GetManySrvName(ids, strEntityNo);
            return strList;
        }
        /// <summary>
        /// 具体详细信息
        /// </summary>
        /// <param name="id">一事一议ID</param>
        /// <returns>视图</returns>
        public ActionResult OnePrjOneDiscusInformation(string id)
        {
            Model.OnePrjOneDiscus onePrjOneDiscusModel = new Model.OnePrjOneDiscus();
            BLL.OnePrjOneDiscus onePrjOneDiscusBll = new BLL.OnePrjOneDiscus();
            id = Fetch.estimateString(id, CheckGetEnum.Safety);
            onePrjOneDiscusModel = onePrjOneDiscusBll.GetModel(decimal.Parse(id));
            ViewData["id"] = id;

            return View(onePrjOneDiscusModel);
        }

    }
}
